import React, { useMemo } from 'react';
import { ck_sn, loc, HandView, obj_str, no_del, PanelFind, filter_row, BtTxt, useCmd, useHigh, Btn, GridTable } from 'sui';
import { useAccess } from 'cache';

const UserView = () => {
    const [high] = useHigh(140, 100);
    const [no_acc] = useAccess();
    const umd = useCmd("file/list/custom");

    const getRow = useMemo(() => {
        const lst = ["sn"];
        return filter_row(umd.value, lst, umd.filter);
    }, [umd.value, umd.filter]);

    const act = {
        "add": (v, h) => umd.update("file/md/custom", {v: v, sn: obj_str(v, "sn")}, h),
    };

    const col = [
        {name: loc("l_193"), key: 'index', width: 70},
        {name: loc("l_238"), key: 'e_opt', width: 120, formatter: (props) => {
            const d = props.row;
            return <BtTxt hcmd={() => hDel(d)} disabled={no_acc("tc")}>{loc("l_237")}</BtTxt>;
        }},
        {name: loc("l_520"), key: 'sn', width: 300},
    ];

    const get_ck = (cur, main, col) => {
        const ret = {
            sn : v => ck_sn(v, cur, main),
        };

        return ret;
    };

    const hCol = () => {
        const ret = [];
        col.forEach(d => {
            if (d.key === "index" || d.key === "e_opt") {
                return;
            }

            ret.push({ sn: d.key, name: d.name });
        });

        return ret;
    };

    if (umd.isFin("add")) {
        return <HandView umd={umd} title={loc("l_739")} act={act} col={hCol()} ck={get_ck(umd.cur, umd.value, col)}/>;
    }

    const hDel = (val) => {
        if (no_del()) {
            return;
        }

        umd.update("file/rm/custom", {sn: obj_str(val, "sn")});
    };

    const Right = () => <Btn color="green" hcmd={() => umd.pact(null, null, "add")} className="ml-4" disabled={no_acc("tc")}>{loc("l_239")}</Btn>;

    return (
        <div className="flex flex-col">
            <PanelFind left={loc("l_520")} right={<Right/>} hcmd={umd.setFilter}/>
            <GridTable high={high} col={col} row={getRow}/>
        </div>
    );
};

export {UserView};
